package org.example.learn.javaagent.apply_demo.plugin.impl.link;

import net.bytebuddy.asm.Advice;
import org.example.learn.javaagent.apply_demo.track.Span;
import org.example.learn.javaagent.apply_demo.track.TrackContext;
import org.example.learn.javaagent.apply_demo.track.TrackManager;

import java.util.UUID;

// 链路追踪 通知类
public class LinkAdvice {

    // 进入方法事件
    @Advice.OnMethodEnter()
    public static void enter(@Advice.Origin("#t") String className,@Advice.Origin("#m") String methodName){
        Span currentSpan = TrackManager.getCurrentSpan();
        if (null == currentSpan) {
            String linkId = UUID.randomUUID().toString();
            TrackContext.setLinkId(linkId);
        }
        TrackManager.createEntrySpan();
    }

    @Advice.OnMethodExit()
    public static void exit(@Advice.Origin("#t") String className,@Advice.Origin("#m") String methodName){
        Span span = TrackManager.getExitSpan();
        if (null == span){
            return;
        }
        System.out.println("链路追踪：" + span.getLinkId() + " " + className + " " + methodName + " 耗时：" + (System.currentTimeMillis() - span.getEnterTime().getTime()) + "ms");
    }
}
